﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Windows.Forms;
using WenSkin.Controls.ListBoxControl;

namespace WenSkin.Controls
{
    [Designer(typeof(Design.Designer.WenListBoxControlDesigner))]
    public class WenListBoxControl : WenControl
    {
        public WenListBoxControl() : base()
        {
            flow = new FlowLayoutPanel()
            {
                Dock = DockStyle.Fill,
                AutoScroll = true,
                BorderStyle = BorderStyle.FixedSingle
            };
            this.Controls.Add(flow);
            Size = new Size(120, 120);
        }

        private FlowLayoutPanel flow;
        private WenListBoxControlItemCollection items;

        protected override void OnSizeChanged(EventArgs e)
        {
            base.OnSizeChanged(e);
            if (!AutoItemHight)
                foreach (Control control in flow.Controls)
                {
                    control.Width = this.Width - 25;
                }
        }

        #region 委托
        public delegate void ButtonClickEventHandler(object sender, ButtonClickEventArgs e);

        public class ButtonClickEventArgs : EventArgs
        {
            public object Value { get; set; }
            public Control ItemControl { get; set; }
            public string Text { get; set; }
            public string Name { get; set; }
            public WenListBoxControlItem Item { get; set; }
            public bool State { get; set; } = true;
        }

        public event ButtonClickEventHandler ButtonClick;
        public event ButtonClickEventHandler RemoveClick;
        public event ButtonClickEventHandler RemoveItemBeforeChanged;
        public event ButtonClickEventHandler ItemClick;

        protected virtual void OnRemoveClick(ButtonClickEventArgs e)
        {
            RemoveClick?.Invoke(this, e);
        }
        protected virtual void OnButtonClick(ButtonClickEventArgs e)
        {
            ButtonClick?.Invoke(this, e);
        }
        
        protected virtual void OnItemClick(ButtonClickEventArgs e)
        {
            ItemClick?.Invoke(this, e);
        }
        #endregion

        #region 公有属性

        [Category("Wen"), Description("选项值"), DefaultValue(null), DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        [Editor(typeof(Design.Editor.WenCollectionEditor), typeof(System.Drawing.Design.UITypeEditor))]
        public WenListBoxControlItemCollection Items => items ??= new WenListBoxControlItemCollection(this);

        [Category("Wen"), Description("设置模板 类请用typeof(Class)"), DefaultValue(typeof(WenListBoxControlItemTemplate))]
        public Type Template { get; set; } = typeof(WenListBoxControlItemTemplate);

        [Category("Wen"), Description("设置当行的高度"), DefaultValue(30)]
        public int ItemHight { get; set; } = 30;

        [Category("Wen"), Description("是否自动大小"), DefaultValue(false)]
        public bool AutoItemHight { get; set; } = false;

        [Category("Wen"), Description("是否显示删除按钮"), DefaultValue(true)]
        public bool RemoveButtonShow { get; set; } = true;

        [Category("WenImage"), Description("是否显示自定义按钮"), DefaultValue(true)]
        public bool ButtonShow { get; set; } = true;
        [Category("WenImage"), Description("自定义按钮图标"), DefaultValue(true)]
        public Image ButtonImage { get; set; }
        #endregion

        #region 绑定数据
        [Category("WenData"), Description("绑定数据列"), DefaultValue(null)]
        public string ColumnName { get; set; }
        private object dataSource { get; set; }
        [Browsable(false)]
        public object DataSource
        {
            get => dataSource;
            set
            {
                if (value != null)
                {
                    dataSource = value;
                    DataBind();
                }
            }
        }
        private void DataBind()
        {
            if (dataSource == null)
                return;
            this.Items.Clear();

            //分类数据绑定
            switch (dataSource)
            {
                case DataSet ds:
                    DataBindDataTable(ds.Tables[0]);
                    break;
                case DataTable dt:
                    DataBindDataTable(dt);
                    break;
                case System.Collections.IList ilist:
                    if (string.IsNullOrWhiteSpace(ColumnName))
                    {
                        foreach (var li in ilist)
                        {
                            List<System.Reflection.PropertyInfo> propertyInfos = new List<System.Reflection.PropertyInfo>(li.GetType().GetProperties());
                            string value = propertyInfos.Find(a => a.Name.ToUpper() == ColumnName.ToUpper())?.GetValue(li, null)?.ToString();

                            WenListBoxControlItem item = new WenListBoxControlItem()
                            {
                                Text = value,
                                Tag = li
                            };
                            Items.Add(item);

                        }
                    }
                    else
                    {
                        foreach (var li in ilist)
                        {
                            string value = li.GetType().GetProperties()[0].GetValue(li, null)?.ToString();
                            WenListBoxControlItem item = new WenListBoxControlItem()
                            {
                                Text = value,
                                Tag = li
                            };
                            Items.Add(item);
                        }
                    }
                    break;
                default:
                    break;
            }

            //绑定数据   
            void DataBindDataTable(DataTable dt)
            {
                if (string.IsNullOrWhiteSpace(ColumnName))
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        WenListBoxControlItem item = new WenListBoxControlItem()
                        {
                            Text = dr[0]?.ToString(),
                            Tag = dr
                        };
                        Items.Add(item);
                    }
                }
                else
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        WenListBoxControlItem item = new WenListBoxControlItem()
                        {
                            Text = dr[ColumnName]?.ToString(),
                            Tag = dr
                        };
                        Items.Add(dr[ColumnName]);
                    }
                }
            }
        }


        #endregion

        #region  子类

        public class WenListBoxControlItemCollection : WenCollection
        {
            private readonly WenListBoxControl owner;
            public WenListBoxControlItemCollection(WenListBoxControl owner)
            {
                this.owner = owner;
            }

            public WenListBoxControlItem this[int index]
            {
                get => Items[index] as WenListBoxControlItem;
                set
                {
                    if (value is WenListBoxControlItem item)
                        Items[index] = item;
                }
            }
            public WenListBoxControlItem this[string str]
            {
                get => Items.ToArray().ToList().Find(q =>
                (q as WenListBoxControlItem).Text.ToUpper() == str.ToUpper() ||
                (q as WenListBoxControlItem).Name.ToUpper() == str.ToUpper()) as WenListBoxControlItem;
            }

            public override int Add(object value)
            {
                if (value is WenListBoxControlItem controlItem)
                {
                    //自定义模板处理
                    if (controlItem.Template != null)
                    {
                        var type = System.Activator.CreateInstance(owner.Template);
                        if (type is Control control)
                        {
                            control.Text = controlItem.Text;
                            control.Name = controlItem.Name;
                            control.Tag = controlItem.Tag;
                            controlItem.Control = control;
                        }
                    }
                    else if (owner.Template != null)
                    {
                        controlItem.Template = owner.Template;
                        var type = System.Activator.CreateInstance(owner.Template);
                        if (type is Control control)
                        {
                            control.Text = controlItem.Text;
                            control.Name = controlItem.Name;
                            control.Tag = controlItem.Tag;
                            controlItem.Control = control;
                        }
                    }

                    //模板继承控件事件处理
                    if (controlItem.Control is WenListBoxControlItemTemplate template)
                    {
                        template.RemoveButtonShow = owner.RemoveButtonShow;
                        template.ButtonShow = owner.ButtonShow;
                        template.ButtonImage = owner.ButtonImage;
                        ButtonClickEventArgs ex = new ButtonClickEventArgs
                        {
                            Item = controlItem,
                            Text = controlItem.Text,
                            Name = controlItem.Name,
                            ItemControl = controlItem.Control,
                        };
                        //删除按钮点击事件移除内容
                        template.RemoveClick += (s, e) =>
                        {
                            ex.State = true;
                            this.owner.RemoveItemBeforeChanged(owner, ex);
                            if (ex.State)
                            {
                                this.Remove(controlItem);        
                            }
                            this.owner.OnRemoveClick(ex);
                        };
                        //自定义按钮点击事件
                        template.ButtonClick += (s, e) =>
                        {
                            owner.OnButtonClick(ex);
                        };
                        
                        //单击事件
                        template.Click += (s, e) =>
                        {
                            owner.OnItemClick(ex);
                        };
                    }


                    //添加单项
                    owner.flow.Controls.Add(controlItem.Control);

                    //是否自定义尺寸
                    if (!owner.AutoItemHight)
                    {
                        controlItem.Control.Width = owner.Width - 25;
                        controlItem.Control.Height = owner.ItemHight;
                    }
                }
                else
                {
                    return Add(value?.ToString());
                }
                return base.Add(value);
            }

            public int Add(string text)
            {
                WenListBoxControlItem controlItem = new WenListBoxControlItem(text);
                return this.Add(controlItem);
            }
            public override void Clear()
            {
                base.Clear();
                owner.flow.Controls.Clear();
            }
            public override void Remove(object value)
            {
                base.Remove(value);
                if (value is WenListBoxControlItem controlItem)
                {
                    owner.flow.Controls.Remove(controlItem.Control);
                }
            }
            public override void RemoveAt(int index)
            {
                base.RemoveAt(index);
                if (this[index] is WenListBoxControlItem controlItem)
                {
                    owner.flow.Controls.Remove(controlItem.Control);
                }
            }
        }

        public class WenListBoxControlItem
        {
            public WenListBoxControlItem()
            {
                value = "文本";
                Name = "Name";
                Tag = null;
            }
            public WenListBoxControlItem(string text) : this()
            {
                value = text;
            }

            public WenListBoxControlItem(object val)
            {
                value = val;
            }

            #region 私有属性
            private string name;
            private object tag;
            private object value;
            #endregion

            #region 公有属性

            /// <summary>
            /// 控件
            /// </summary>
            [Browsable(false)]
            public Control Control { get; set; }
            /// <summary>
            /// text内容
            /// </summary>
            [Category("Wen"), Description("内容"), DefaultValue(true)]
            public string Text
            {
                get => this.Value?.ToString();
                set => this.Value = value;
            }
            
            /// <summary>
            /// Value值
            /// </summary>
            [Category("Wen"), Description("内容"), DefaultValue(true)]
            public object Value
            {
                get => this.value;
                set
                {
                    this.value = value;
                    if (Control != null)
                    {
                        Control.Text = value?.ToString(); 
                        this.Control.Invalidate();
                    }
                }
            }
            /// <summary>
            /// 名称
            /// </summary>
            [Category("Wen"), Description("名称"), DefaultValue(true)]
            public string Name
            {
                get => name;
                set { name = value; if (Control != null) Control.Name = value; }
            }

            /// <summary>
            /// 绑定数据
            /// </summary>
            [Category("Wen"), Description("绑定数据"), DefaultValue(true)]
            public object Tag
            {
                get => tag;
                set { tag = value; if (Control != null) Control.Tag = value; }
            }
            /// <summary>
            /// 单项模板 请使用typeof(class)
            /// </summary>
            [Browsable(false)]
            [Category("Wen"), Description("单项模板"), DefaultValue(true)]
            public Type Template { get; set; }

            #endregion

            public override string ToString()
            {
                return Text;
            }
        }

        #endregion
    }
}
